package cn.com.cifi.mars.service.impl;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.dto.IdmPositionDto;
import cn.com.cifi.mars.bean.dto.IdmPositionPageDto;
import cn.com.cifi.mars.bean.dto.PositionDetailDto;
import cn.com.cifi.mars.bean.dto.ProjectByStagesDto;
import cn.com.cifi.mars.bean.vo.sys.rsp.IdmPositionPageVo;
import cn.com.cifi.mars.bean.vo.sys.rsp.PositionDetailVo;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.HrOrgTypeEunm;
import cn.com.cifi.mars.constant.IsSuccessEnum;
import cn.com.cifi.mars.constant.LogEventEnum;
import cn.com.cifi.mars.constant.LogSrcEnum;
import cn.com.cifi.mars.constant.LogTypeEnum;
import cn.com.cifi.mars.entity.common.IdmPosition;
import cn.com.cifi.mars.entity.common.SysPositionGroupAuthorize;
import cn.com.cifi.mars.mapper.mars.IdmPositionMapper;
import cn.com.cifi.mars.mapper.mars.ProjectByStagesMapper;
import cn.com.cifi.mars.mapper.mars.SysPositionGroupAuthorizeMapper;
import cn.com.cifi.mars.service.IdmPositionService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.util.BasicAuthClient;
import cn.com.cifi.mars.util.WebUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class PositionServiceImpl extends ServiceImpl<IdmPositionMapper, IdmPosition> implements IdmPositionService {

	@Autowired
	private IdmPositionMapper idmPositionMapper;
	@Autowired
	private SysPositionGroupAuthorizeMapper sysPositionGroupAuthorizeMapper;
	@Autowired
	private ProjectByStagesMapper projectByStagesMapper;
	@Autowired
	private SysLogService sysLogService;
	
	@Value("${host}")
	private String host;
	
	@Value("${port_idm}")
	private String port_idm;
	
	@Value("${api_name}")
	private String api_name;
	
	@Value("${api_key}")
	private String api_key;
	
	
	@Override
	public List<String> getJobNumList() {
		return idmPositionMapper.selectJobNumList();
	}

	/**
	 * 分页查询组织机构下的--岗位信息
	 */
	@Override
	public IdmPositionPageVo queryOrgPositionPage(String current, String pageSize, String jobName,String belongDepId) {
		IdmPositionPageVo vo=new IdmPositionPageVo();
		Page<IdmPositionPageDto>pageDto=new Page<>();
		//参数当前页
		pageDto.setCurrent(Integer.parseInt(current));
		//参数每页数量
		pageDto.setSize(Integer.parseInt(pageSize));
		List<IdmPositionPageDto>list= idmPositionMapper.selectOrgPositionPage(pageDto, jobName,belongDepId);
		vo.setCurrent(pageDto.getCurrent());
		vo.setPages(pageDto.getPages());
		vo.setPageSize(pageDto.getSize());
		vo.setTotal(pageDto.getTotal());
		vo.setList(list);
		return vo;
	}
	
	/**
	 * 岗位明细分页
	 */
	@Override
	public PositionDetailVo queryPositionDetailPage(String current, String pageSize, String jobName,
			String belongJobDefId) {
		Page<PositionDetailDto>pageDto=new Page<PositionDetailDto>();
		//参数当前页
		pageDto.setCurrent(Integer.parseInt(current));
		//参数每页数量
		pageDto.setSize(Integer.parseInt(pageSize));
		
		QueryWrapper<SysPositionGroupAuthorize>queryWrapper=new QueryWrapper<>();
		queryWrapper.eq("position_group_id", belongJobDefId);
		SysPositionGroupAuthorize sysPositionGroupAuthorize=sysPositionGroupAuthorizeMapper.selectOne(queryWrapper);
		
		List<PositionDetailDto>list=idmPositionMapper.selectPositionDetailPage(pageDto, jobName, belongJobDefId);
		for (PositionDetailDto dto : list) {
			//获取岗位权限名称
			List<String>orgids=idmPositionMapper.selectOrgidsByPositionId(dto.getJobNum());
			HashSet<String>nameList=new HashSet<>();
			for (String orgid : orgids) {
				//根据组织机构id获取项目名称 
				List<String> names=idmPositionMapper.selectPermissionName(orgid);
				nameList.addAll(names);
			}
			if(sysPositionGroupAuthorize!=null) {
				//自动授权给这个岗位组下面对应的一个岗位授权
				if(StringUtils.isNotBlank(dto.getBelongDepFullNo())) {
					 List<String> orgdepids=getGroupOrgIds(dto.getBelongDepFullNo());
					 getPerssionName(orgdepids,nameList);
				}
			}
			dto.setPerName(nameList);
		}
		//分页和list
		PositionDetailVo vo=new PositionDetailVo();
		vo.setCurrent(pageDto.getCurrent());
		vo.setPages(pageDto.getPages());
		vo.setPageSize(pageDto.getSize());
		vo.setTotal(pageDto.getTotal());
		vo.setList(list);
		return vo;
	}

	/**
	 * 根据岗位名称查询岗位下的用户
	 */
	@Override
	public List<String> getUserByJobName(String jobName) {
		return idmPositionMapper.selectByPositionname(jobName);
	}
	
	/**
	 * 获取自动授权的岗位组的组织机构id
	 * @param orgnofullpath
	 * @return
	 */
	public List<String> getGroupOrgIds(String belongDepFullNo) {
		List<String>orgids=new ArrayList<>();
		String []path=belongDepFullNo.split("-");
		for (int i=path.length-1;i>=0;i--) {
			String str=path[i];
			ProjectByStagesDto bb =projectByStagesMapper.selectByOrgdepid(str);
			if(bb!=null) {
				if(StringUtils.isNotBlank(bb.getHrOrgTypeId())) {
					if(bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_31.getKey())) {
						orgids.add(str);
						break;
					}else if(bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_23.getKey())) {
						orgids.add(str);
						break;
					}else if(bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_21.getKey())) {
						orgids.add(str);
						break;
					}else if(bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_20.getKey())) {
						orgids.add(str);
						break;
					}else if(bb.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_11.getKey())) {
						orgids.add(str);
						break;
					}
				}
			}
		}
		return orgids;
	}
	
	/**
	 * 优化岗位组->数据权限-》自动授权的组织机构的名称
	 * @param pbs
	 * @return
	 */
	public HashSet<String> getPerssionName(List<String>positionIds,HashSet<String>list) {
		if(positionIds.size()==0) {
			return list;
		}
		//旭辉集团的 全部查出来
		List<String>xhIds=projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_11.getKey());
				
		//区域的id 全部查出来
		List<String>regionIds=projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_20.getKey());
		//城市公司的id 全部查出来
		List<String>cityIds=projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_21.getKey());
		//直管项目的id 全部查出来
		List<String>tubeIds=projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_23.getKey());
		//项目的id 全部查出来
		List<String>projectIds=projectByStagesMapper.selectStagesByPositionGroupIds(positionIds, HrOrgTypeEunm.ORG_31.getKey());
		
		if(xhIds.size()>0) {
			List<ProjectByStagesDto>xhList=projectByStagesMapper.selectRoleOrgList(xhIds);
			list.addAll(addOrgName(xhList));
		}
		if(regionIds.size()>0) {
			List<ProjectByStagesDto>regionList=projectByStagesMapper.selectRoleOrgList(regionIds);
			list.addAll(addOrgName(regionList));
		}
		if(cityIds.size()>0) {
			//根据城市id获取城市和城市以下所有数据
			List<ProjectByStagesDto>cityList=projectByStagesMapper.selectRoleOrgList(cityIds);
			//根据城市id获取区域信息
			List<ProjectByStagesDto>regionList=projectByStagesMapper.selectOrgParentList(cityIds);
			list.addAll(addOrgName(cityList));
			list.addAll(addOrgName(regionList));
		}
		if(tubeIds.size()>0) {
			//根据直管项目id获取直管项目和以下所有数据
			List<ProjectByStagesDto>tubeList=projectByStagesMapper.selectRoleOrgList(tubeIds);
			//根据直管项目id获取区域信息
			List<ProjectByStagesDto>regionList=projectByStagesMapper.selectOrgParentList(tubeIds);
			list.addAll(addOrgName(tubeList));
			list.addAll(addOrgName(regionList));
		}
		if(projectIds.size()>0) {
			//根据项目id获取项目和以下所有数据
			List<ProjectByStagesDto>projectList=projectByStagesMapper.selectRoleOrgList(projectIds);
			//根据项目id获取城市公司信息
			List<ProjectByStagesDto>cityList=projectByStagesMapper.selectOrgParentList(projectIds);
			List<String>cityStr=new ArrayList<>();
			for (ProjectByStagesDto c : cityList) {
				cityStr.add(c.getOrgdepid());
			}
			//根据城市公司id获取区域信息
			List<ProjectByStagesDto>regionList=projectByStagesMapper.selectOrgParentList(cityStr);
			list.addAll(addOrgName(projectList));
			list.addAll(addOrgName(cityList));
			list.addAll(addOrgName(regionList));
		}
		return list;
	}
	
	/**
	 * 优化存放项目
	 * @param list
	 * @return
	 */
	public HashSet<String> addOrgName(List<ProjectByStagesDto>list) {
		HashSet<String>strs=new HashSet<>();
		for (ProjectByStagesDto p : list) {
			if(p.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_31.getKey())) {
				String name=p.getOrgname();
				strs.add(name);
			}
			if(p.getHrOrgTypeId().equals(HrOrgTypeEunm.ORG_23.getKey())) {
				String name=p.getOrgname();
				strs.add(name);
			}
		}
		return strs;
	}
	
	/**
	 * 增量同步岗位
	 */
	@Transactional
	@Override
	public String syncPosition(String timestamp, String cookie,String jobNumStr,List<String>jobNums) {
		BasicAuthClient bac = new BasicAuthClient();
		String url = host+"/idm/jobs/query";
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		if("0".equals(cookie)||"null".equals(cookie)) {
			
		}else {
			String[] cookies=cookie.split(",");
			cookie=BasicAuthClient.encryptionCookie(cookies);
		}
		String jsonParam = "{\"esbInfo\":{\"instId\":\"\",\"requestTime\":\""+requestTime+"\"},\"requestInfo\":{\"timestamp\":\""+timestamp+"\",\"cookie\":"+"\""+cookie+"\""+",\"basedn\":\"ou=jobs,ou=JobPortfolios,dc=bizenit,dc=com\",\"filter\":\"(cn="+jobNumStr+")\"}}";
		String result = bac.post(url,jsonParam,api_name,api_key);
		JSONObject jsonObject=JSONObject.parseObject(result);
		JSONObject esbInfo=jsonObject.getJSONObject("esbInfo");
		String returnMsg=esbInfo.getString("returnMsg");
		log.info("######### 同步岗位数据请求参数："+jsonParam);
		if(returnMsg.equals("success")) {
			JSONObject resultInfo=jsonObject.getJSONObject("resultInfo");
			JSONArray results=(JSONArray) resultInfo.get("results");
			JSONArray cookies=(JSONArray) resultInfo.get("cookie");
			List<IdmPosition>list=new ArrayList<>();
			for (int i = 0; i < results.size(); i++) {
				String jobName=results.getJSONObject(i).getString("jobName");
				String jobNum=results.getJSONObject(i).getString("jobNum");
				String jobStatus=results.getJSONObject(i).getString("jobStatus");
				String belongDepFullNo=results.getJSONObject(i).getString("belongDepFullNo");
				String jobcategory=results.getJSONObject(i).getString("jobcategory");
				String belongDepFullName=results.getJSONObject(i).getString("belongDepFullName");
				String belongJobDefId=results.getJSONObject(i).getString("belongJobDefId");
				String jobType=results.getJSONObject(i).getString("jobType");
				String belongDepId=results.getJSONObject(i).getString("belongDepId");
				if(jobcategory.equals("null")) {
					jobcategory="";
				}
				if(belongDepFullName.equals("null")) {
					belongDepFullName="";
				}
				if(belongDepFullNo.equals("null")) {
					belongDepFullNo="";
				}
				
				IdmPosition pos=new IdmPosition();
				pos.setJobName(jobName);
				pos.setJobNum(jobNum);
				pos.setJobStatus(jobStatus);
				pos.setBelongJobDefId(belongJobDefId);
				pos.setBelongDepFullName(belongDepFullName);
				pos.setJobType(jobType);
				pos.setBelongDepFullNo(belongDepFullNo);
				pos.setJobcategory(jobcategory);
				pos.setBelongDepId(belongDepId);
				list.add(pos);
			}
			List<IdmPosition> saveList =new ArrayList<>();
			List<IdmPosition> updateList =new ArrayList<>();
			for (IdmPosition up : list) {
				if(jobNums.contains(up.getJobNum())) {
					updateList.add(up);
				}					
			}
			for (IdmPosition sa : list) {
				if(!jobNums.contains(sa.getJobNum())) {
					saveList.add(sa);
				}	
			}
			this.saveBatch(saveList);
			this.saveOrUpdateBatch(updateList);
			
			String addStr = getPosition(saveList);
            String updateStr = getPosition(updateList);
            saveLog("增量同步IDM岗位信息","请求参数：" + url+jsonParam + ";响应数据：新增岗位：" + addStr+"&&更新岗位："+updateStr);
			if(cookies!=null) {
				String ck=cookies.toString().replace("[","").replace("]","");
				syncPosition(timestamp,ck,jobNumStr,jobNums);
			}
			return "响应数据：新增岗位：" + addStr+"&&更新岗位："+updateStr;
		}else {
			return returnMsg;
		}
	}
	
	 private String getPosition(List<IdmPosition> addList) {
    	StringBuilder sb = new StringBuilder();
    	for(IdmPosition org : addList) {
    		sb.append(org.getJobNum()).append("|").append(org.getJobName()).append(";");
		}
		return sb.toString();
	 }
	 
	 private void saveLog(String title,String content) {
        SysLogBO bo = new SysLogBO();
        bo.setEvent(LogEventEnum.TIMERTASK);
        bo.setSource(LogSrcEnum.SYS);
        String hostAddr =WebUtils.getLocalIP();
        bo.setIp(hostAddr);
        bo.setModule("同步IDM岗位信息");
        bo.setTitle(title);
        bo.setContent(content);
        bo.setType(LogTypeEnum.ONE.getKey());
        bo.setIsSuccess(IsSuccessEnum.SUCCESS.getKey());
        sysLogService.add(bo,Constants.SYS);
     }
}
